package gui;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

import app.Cookbook;
import app.Ingredient;
import app.Recipe;

/********************************************************
 *
 *  Project :  TeamProject
 *  Package :  gui
 *  File    :  PrintRecipePanel.java
 *  Name    :  Tyler Daines
 *  Date    :  Nov 19, 2013
 *
 ********************************************************/
public class PrintRecipePanel extends JPanel implements Printable
{
	private String instructions;	
	private BufferedImage image; 
	private ArrayList<Ingredient> ingredients;
	private Cookbook cookbook;
	private int[] pageBreaks;
	private ArrayList<String> textLines;
	
	/********************************************************
	 * Name       : Print
	 * Purpose    : Constructor
	 * Parameters : 
	 ********************************************************/
	public PrintRecipePanel(Recipe recipe)
	{
		cookbook = new Cookbook();
		textLines = new ArrayList<>();
		pageSetup(recipe);
		setBackground(Color.WHITE);
		
	}
	

	@Override
	public void paint(Graphics g)
	{
		super.paint(g);
		Graphics2D g2d = (Graphics2D) g;
		int x = 5;
		int y = 15;
		Font font = new Font("Serif", Font.PLAIN, 12);
		FontMetrics metrics = g2d.getFontMetrics(font);
		int lineHeight = metrics.getHeight();
		
		g2d.drawImage(image, null, x+metrics.stringWidth(textLines.get(0))+200, y);
        
        for (int i= 0; i< textLines.size(); i++) 
        {
            y += lineHeight;
            g2d.drawString(textLines.get(i), x, y);
            
        }
	}




	@Override
	public int print(Graphics g, PageFormat pf, int page)
			throws PrinterException
	{
		int numberOfLines = 0;
		
		Graphics2D g2d = (Graphics2D) g;
		int x =  (int) pf.getImageableX()+10;
		int y = (int) pf.getImageableY();
		g2d.translate(x, y);
		
		Font font = new Font("Serif", Font.PLAIN, 14);
		FontMetrics metrics = g2d.getFontMetrics(font);
		int lineHeight = metrics.getHeight();			
		
		if(pageBreaks == null)
		{
			int linesPerPage = (int) (pf.getImageableHeight()/lineHeight);
			int numBreaks = (textLines.size())/linesPerPage;
			pageBreaks = new int[numBreaks];
			for(int i = 0; i < numBreaks; i++)
			{
				pageBreaks[i] = (i+1)*linesPerPage;
			}
		}
		
		if(page > pageBreaks.length)
			return NO_SUCH_PAGE;
		
		if(page == 0)
		{
			g2d.drawImage(image, x+275, y+25, 275, 275, null);
		}
		
        int start = (page == 0) ? 0 : pageBreaks[page-1];
        int end   = (page == pageBreaks.length)
                         ? textLines.size() : pageBreaks[page];
        for (int line=start; line<end; line++) 
        {
            y += lineHeight;
            g2d.drawString(textLines.get(line), x, y);
        }
        
        
 
		
		return PAGE_EXISTS;
	}
	
	/********************************************************
	* Name       : pageSetup
	* Purpose    : 
	* Parameters : 
	* Returns    : void
	********************************************************/
	private void pageSetup(Recipe recipe)
	{
		
		textLines.add("");
		textLines.add("Name: "+recipe.getName());
		textLines.add("# of Servings: "+recipe.getServingSize());
		textLines.add("Category: "+cookbook.pullCategory(recipe.getCategoryID()));
		textLines.add("Calories: "+recipe.getCalories());
		ingredients = recipe.getIngredients();
		instructions = recipe.getDirections();
		
		textLines.add("");
		textLines.add("Ingredients: ");
		for(int i = 0; i < ingredients.size(); i++)
		{
			textLines.add("  "+ingredients.get(i).getAmount()+" "+ingredients.get(i).getMeasurement().toString()+
					" "+ingredients.get(i).getName());
		}
		if(ingredients.size() < 10)
		{
			for(int i = 0; i< (10-ingredients.size()); i++ )
			{
				textLines.add("");
			}
		}
		textLines.add("");
		textLines.add("Directions: ");
		
		StringTokenizer stringTokenizer = new StringTokenizer(instructions, " ");
		StringBuilder output = new StringBuilder();
		
		int lineLen = 0;
		while(stringTokenizer.hasMoreTokens())
		{
			
			String word = stringTokenizer.nextToken()+" ";
			
			if((lineLen + word.length()) > 100)
			{
				textLines.add("  "+output.toString());
				lineLen = 0;
				output = new StringBuilder();
			}
			output.append(word);
			lineLen += word.length();
		}
		textLines.add(output.toString());
		
		try
		{
			
			if(!recipe.getPicture().equals("/resources/recipes.png"))
			{
				File file = new File(recipe.getPicture());
				image = ImageIO.read(file);
			}		
			else
				image = ImageIO.read(getClass().getResource(recipe.getPicture()));
			
			
		}
		catch (IOException e)
		{
			if(e.getMessage().equals("Can't read input file!"))
			{
				try
				{
					image = ImageIO.read(getClass().getResource("/resources/recipes.png"));
				}
				catch (IOException e1)
				{
					System.err.println(e1.getMessage());
				}
			}
		}
	}

}
